package com.zlj.jdbc.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class TestJdbcUtils02 {
	
	/*
	 * 测试
	 */
	@Test
	public void test01() throws SQLException {
		JdbcUtils02.getInstance().getConnection();
		
		//测试单笔查询
		Employee querySingle = querySingle(5);
		System.out.println(querySingle);
		
		System.out.println("------------");
		
		//测试多笔查询
		List<Employee> queryMore = queryMore();
		for (Employee employee : queryMore) {
			System.out.println(employee);
		}
	}
	
    @SuppressWarnings("unchecked")
	public Employee querySingle(int id) throws SQLException {
    	String sql = "select * from employee where id = ?";
    	Object[] params = {id};
    	RsHandler<Employee> rh = new RsHandler<Employee>() {
			@Override
			public Employee handler(ResultSet rs) throws SQLException {
				Employee emp = new Employee();
				while(rs.next()) {
					emp.setId(rs.getInt("id"));
					emp.setName(rs.getString("name"));
					emp.setEmail(rs.getString("email"));
					emp.setGender(rs.getString("gender"));
				}
				return emp;
			}
    	};
    	return (Employee) JdbcUtils02.getInstance().querySingleResult(sql, rh, params);
    }
    
    @SuppressWarnings("unchecked")
   	public List<Employee> queryMore() throws SQLException {
       	String sql = "select * from employee";
       	Object[] params = {};
       	RsHandler<List<Employee>> rh = new RsHandler<List<Employee>>() {
   			@Override
   			public List<Employee> handler(ResultSet rs) throws SQLException {
   				List<Employee> employee = new ArrayList<>();
   				while(rs.next()) {
   					Employee emp = new Employee();
   					emp.setId(rs.getInt("id"));
   					emp.setName(rs.getString("name"));
   					emp.setEmail(rs.getString("email"));
   					emp.setGender(rs.getString("gender"));
   					employee.add(emp);
   				}
   				return employee;
   			}
       	};
       	return (List<Employee>) JdbcUtils02.getInstance().queryMoreResult(sql, rh, params);
       }

}
